package com.java110.mall.system.export.adapt;

import com.alibaba.fastjson.JSONObject;
import com.java110.dto.data.ExportDataDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.groupBuy.GroupBuyProductDto;
import com.java110.dto.groupBuy.GroupBuyProductSpecDto;
import com.java110.dto.product.*;
import com.java110.intf.goods.*;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.mall.system.export.IExportDataAdapt;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.cache.UrlCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("storeProductManage")
public class ExportProductManageAdapt implements IExportDataAdapt {

    private static final int MAX_ROW = 60000;

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductSpecDetailInnerServiceSMO productSpecDetailInnerServiceSMOImpl;

    @Autowired
    private IGroupBuyProductInnerServiceSMO groupBuyProductInnerServiceSMOImpl;


    @Autowired
    private IGroupBuyProductSpecInnerServiceSMO groupBuyProductSpecInnerServiceSMOImpl;


    @Override
    public SXSSFWorkbook exportData(ExportDataDto exportDataDto) {
        SXSSFWorkbook workbook = null;  //工作簿
        //工作表
        workbook = new SXSSFWorkbook();
        workbook.setCompressTempFiles(false);

        Sheet sheet = workbook.createSheet("订单信息表");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("商品ID");
        row.createCell(1).setCellValue("商品图片");
        row.createCell(2).setCellValue("商品分组");
        row.createCell(3).setCellValue("商品名称");
        row.createCell(4).setCellValue("仓库");
        row.createCell(5).setCellValue("销量");
        row.createCell(6).setCellValue("库存");
        row.createCell(7).setCellValue("价格");
        row.createCell(8).setCellValue("排序");
        row.createCell(9).setCellValue("状态");
        row.createCell(10).setCellValue("创建时间");

        JSONObject reqJson = exportDataDto.getReqJson();
        ProductDto productDto = BeanConvertUtil.covertBean(reqJson, ProductDto.class);

        //查询数据
        getReprotData(sheet, productDto);

        return workbook;
    }

    private void getReprotData(Sheet sheet, ProductDto productDto) {
        productDto.setPage(1);
        productDto.setRow(MAX_ROW);
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
        freshProductDtos(productDtos);

        setData(productDtos, sheet, 0);
    }

    private void setData(List<ProductDto> productDtos, Sheet sheet, int step) {
        Row row = null;
        ProductDto productDto = null;
        for (int rowIndex = 0; rowIndex < productDtos.size(); rowIndex++) {
            row = sheet.createRow(rowIndex + step + 1);
            productDto = productDtos.get(rowIndex);
            row.createCell(0).setCellValue(productDto.getProductId());
            row.createCell(1).setCellValue(productDto.getCoverPhoto());
            row.createCell(2).setCellValue(productDto.getCategoryName());
            row.createCell(3).setCellValue(productDto.getProdName());
            row.createCell(4).setCellValue(productDto.getShName());
            row.createCell(5).setCellValue(productDto.getSales());
            row.createCell(6).setCellValue(productDto.getStock());
            row.createCell(7).setCellValue(productDto.getDefaultSpecValue().getPrice());
            row.createCell(8).setCellValue(productDto.getSort());
            row.createCell(9).setCellValue(productDto.getStateName());
            row.createCell(10).setCellValue(DateUtil.getFormatTimeStringA(productDto.getCreateTime()));
        }
    }

    private void freshProductDtos(List<ProductDto> productDtos) {

        if (ListUtil.isNull(productDtos)) {
            return;
        }

        //输入
        List<String> productIds = new ArrayList<>();

        for (ProductDto tmpProductDto : productDtos) {
            productIds.add(tmpProductDto.getProductId());
        }

        FileRelDto fileRelDto = new FileRelDto();
        fileRelDto.setObjIds(productIds.toArray(new String[productIds.size()]));
        fileRelDto.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_COVER);
        List<FileRelDto> fileRelDtos = fileRelInnerServiceSMOImpl.queryFileRels(fileRelDto);

        //刷入图片信息
        List<String> photoVos = null;
        String url = null;
        String mallApp = UrlCache.getMallAppUrl();
        String imgUrl = MappingCache.getValue(MappingConstant.FILE_DOMAIN, "IMG_PATH");
        imgUrl += (!StringUtil.isEmpty(imgUrl) && imgUrl.endsWith("/") ? "" : "/");
        mallApp = mallApp.endsWith("/") ? mallApp : mallApp + "/";

        for (ProductDto tmpProductDto : productDtos) {
            tmpProductDto.setPageUrl(mallApp + "#/pages/goods/goods?productId=" + tmpProductDto.getProductId() + "&shopId=" + tmpProductDto.getShopId());
            for (FileRelDto tmpFileRelDto : fileRelDtos) {
                if (!tmpProductDto.getProductId().equals(tmpFileRelDto.getObjId())) {
                    //url = "/callComponent/download/getFile/file?fileId=" + tmpFileRelDto.getFileRealName() + "&communityId=-1";
                    continue;
                }
                if (StringUtil.isEmpty(tmpFileRelDto.getFileRealName())) {
                    continue;
                }
                url = imgUrl + tmpFileRelDto.getFileRealName();
                if (tmpFileRelDto.getFileRealName().startsWith("http")) {
                    url = tmpFileRelDto.getFileRealName();
                }

                tmpProductDto.setCoverPhoto(url);
            }
        }

        //刷入库存和销量
        ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
        productSpecValueDto.setStoreId(productDtos.get(0).getStoreId());
        productSpecValueDto.setProductIds(productIds.toArray(new String[productIds.size()]));
        List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductStockAndSales(productSpecValueDto);

        for (ProductDto tmpProduct : productDtos) {
            for (ProductSpecValueDto tmpProdSpecValue : productSpecValueDtos) {
                if (tmpProdSpecValue.getProductId().equals(tmpProduct.getProductId())) {
                    tmpProduct.setSales(tmpProdSpecValue.getSales());
                    tmpProduct.setStock(tmpProdSpecValue.getStock());
                }
            }
        }

        // 查询规格
        if (productDtos.size() > 1) {
            return;
        }

        //输入轮播图
        fileRelDto = new FileRelDto();
        fileRelDto.setObjId(productDtos.get(0).getProductId());
        fileRelDto.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        fileRelDtos = fileRelInnerServiceSMOImpl.queryFileRels(fileRelDto);
        List<String> photos = new ArrayList<>();
        for (ProductDto tmpProductDto : productDtos) {
            for (FileRelDto tmpFileRelDto : fileRelDtos) {
                if (tmpProductDto.getProductId().equals(tmpFileRelDto.getObjId())) {
                    //url = "/callComponent/download/getFile/file?fileId=" + tmpFileRelDto.getFileRealName() + "&communityId=-1"
                    if (!tmpFileRelDto.getFileRealName().startsWith("http")) {
                        url = imgUrl + tmpFileRelDto.getFileRealName();
                    } else {
                        url = tmpFileRelDto.getFileRealName();
                    }
                    photos.add(url);
                }
            }
            tmpProductDto.setCarouselFigurePhotos(photos);
        }

        freshProductSpecValue(productDtos.get(0));
        judgeGroupBuyProduct(productDtos.get(0));

        ProductDetailDto productDetailDto = new ProductDetailDto();
        productDetailDto.setProductId(productDtos.get(0).getProductId());
        productDetailDto.setStoreId(productDtos.get(0).getStoreId());
        List<ProductDetailDto> productDetailDtos = productDetailInnerServiceSMOImpl.queryProductDetails(productDetailDto);

        if (ListUtil.isNull(productDetailDtos)) {
            return;
        }

        productDtos.get(0).setContent(productDetailDtos.get(0).getContent());
    }


    private void judgeGroupBuyProduct(ProductDto productDto) {
        //判断商品是否 拼团
        GroupBuyProductDto groupBuyProductDto = new GroupBuyProductDto();
        groupBuyProductDto.setProductId(productDto.getProductId());
        groupBuyProductDto.setStoreId(productDto.getStoreId());
        List<GroupBuyProductDto> groupBuyProductDtos = groupBuyProductInnerServiceSMOImpl.queryGroupBuyProducts(groupBuyProductDto);

        if (ListUtil.isNull(groupBuyProductDtos)) {
            return;
        }

        productDto.setActType(ProductActivityDto.ACT_TYPE_GROUP);
        productDto.setActEndTime(groupBuyProductDtos.get(0).getBatchEndTime());
        productDto.setActProdName(groupBuyProductDtos.get(0).getGroupProdName());
        productDto.setActProdDesc(groupBuyProductDtos.get(0).getGroupProdDesc());

        GroupBuyProductSpecDto groupBuyProductSpecDto = new GroupBuyProductSpecDto();
        groupBuyProductSpecDto.setStoreId(groupBuyProductDtos.get(0).getStoreId());
        groupBuyProductSpecDto.setProductId(groupBuyProductDtos.get(0).getProductId());
        groupBuyProductSpecInnerServiceSMOImpl.queryGroupBuyProductSpecs(groupBuyProductSpecDto);


    }

    private void freshProductSpecValue(ProductDto productDto) {
        ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
        productSpecValueDto.setProductId(productDto.getProductId());
        productSpecValueDto.setStoreId(productDto.getStoreId());
        List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);

        if (ListUtil.isNull(productSpecValueDtos)) {
            return;
        }
        productDto.setProductSpecValues(productSpecValueDtos);

        List<String> specIds = new ArrayList<>();
        for (ProductSpecValueDto productSpecValue : productSpecValueDtos) {
            specIds.add(productSpecValue.getSpecId());
        }

        ProductSpecDetailDto productSpecDetailDto = new ProductSpecDetailDto();
        productSpecDetailDto.setSpecIds(specIds.toArray(new String[specIds.size()]));
        productSpecDetailDto.setStoreId(productDto.getStoreId());
        List<ProductSpecDetailDto> productSpecDetailDtos = productSpecDetailInnerServiceSMOImpl.queryProductSpecDetails(productSpecDetailDto);
        List<ProductSpecDetailDto> tmpProductSpecDetailDtos = null;
        for (ProductSpecValueDto productSpecValue : productSpecValueDtos) {
            tmpProductSpecDetailDtos = new ArrayList<>();
            for (ProductSpecDetailDto tmpProductSpecDetailDto : productSpecDetailDtos) {
                if (productSpecValue.getSpecId().equals(tmpProductSpecDetailDto.getSpecId())) {
                    tmpProductSpecDetailDtos.add(tmpProductSpecDetailDto);
                }
            }
            productSpecValue.setProductSpecDetails(tmpProductSpecDetailDtos);
        }
    }

}
